from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
from config import Config
from image_utils import *
import os

app = Flask(__name__)
app.config.from_object(Config)

# 确保目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['PROCESSED_FOLDER'], exist_ok=True)
os.makedirs(os.path.join('static', 'fonts'), exist_ok=True)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/process', methods=['POST'])
def process():
    processed_files = []
    watermark_type = request.form.get('watermark_type')
    
    # 获取处理参数
    target_size = request.form.get('size')
    output_format = request.form.get('format')
    text = request.form.get('text')
    font_path = os.path.join(os.path.dirname(__file__), 'static', 'fonts', 'arial.ttf')
    
    # 如果字体文件不存在，尝试使用系统字体
    if not os.path.exists(font_path):
        # 在Windows上尝试使用系统字体
        system_font = os.path.join(os.environ.get('WINDIR', 'C:\\Windows'), 'Fonts', 'Arial.ttf')
        if os.path.exists(system_font):
            font_path = system_font
    
    text_color = request.form.get('text_color', '#000000')
    text_position = request.form.get('position', 'bottom_right')
    text_opacity = float(request.form.get('text_opacity', 0.5))
    
    image_watermark = request.files.get('image_watermark')
    image_position = request.form.get('position', 'bottom_right')
    image_opacity = float(request.form.get('image_opacity', 0.5))
    
    # 处理上传的文件
    for file in request.files.getlist('files'):
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            input_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(input_path)
            
            try:
                image = Image.open(input_path)
                
                # 调整尺寸
                if target_size:
                    size_tuple = parse_size(target_size)
                    image = resize_image(image, size_tuple)
                
                # 添加水印
                if watermark_type == 'text' and text:
                    color = ImageColor.getrgb(text_color)
                    image = add_text_watermark(
                        image,
                        text=text,
                        font_path=font_path,
                        font_size=20,
                        color=color,
                        position=text_position,
                        opacity=text_opacity
                    )
                elif watermark_type == 'image' and image_watermark and image_watermark.filename:
                    # 保存临时水印文件
                    wm_filename = f"{uuid.uuid4()}.png"
                    wm_path = os.path.join(app.config['UPLOAD_FOLDER'], wm_filename)
                    image_watermark.save(wm_path)
                    
                    image = add_image_watermark(
                        image,
                        watermark_path=wm_path,
                        position=image_position,
                        opacity=image_opacity
                    )
                    os.remove(wm_path)  # 删除临时文件
                
                # 保存处理后的文件
                output_ext = output_format or os.path.splitext(filename)[1][1:] or 'jpg'
                output_filename = f"{uuid.uuid4()}.{output_ext}"
                output_path = os.path.join(app.config['PROCESSED_FOLDER'], output_filename)
                if image.mode == 'RGBA' and output_ext.lower() == 'jpg':
                    image = image.convert('RGB')
                image.save(output_path)
                processed_files.append(output_filename)
                
            except Exception as e:
                print(f"处理 {filename} 失败: {str(e)}")
    
    return render_template('result.html', files=processed_files)

@app.route('/download/<path:filename>')
def download(filename):
    return send_from_directory(
        app.config['PROCESSED_FOLDER'],
        filename,
        as_attachment=True
    )

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)